//后端接口访问
import axios from 'axios';
import qs from 'qs';

const BASE_URL = 'https://api.huhuiyu.top';
const TOKEM_KET = BASE_URL + '_token';

//本地token信息处理对象
const LocaLtoken = {
  save: (data) => {
    if (data && data.token) {
      localStorage.setItem(TOKEM_KET, data.token);
    }
  },
  load: () => {
    let token = localStorage.getItem(TOKEM_KET);
    return token ? token : '';
  },
};

const Api = {
  get: (url, param, cb) => {
    Api.ajax(url, param, cb, 'get');
  },
  post: (url, param, cb) => {
    Api.ajax(url, param, cb, 'post');
  },
  put: (url, param, cb) => {
    Api.ajax(url, param, cb, 'put');
  },
  delete: (url, param, cb) => {
    Api.ajax(url, param, cb, 'delete');
  },
  patch: (url, param, cb) => {
    Api.ajax(url, param, cb, 'patch');
  },

  ajax: (url, param, cb, method) => {
    //如果是get请求，参数要通过地址栏查询字符串递交
    if (method == 'get') {
      url += '?' + qs.stringify(param, { allowDots: true });
      param = '';
    }

    //发起请求
    const promise = axios({
      url: BASE_URL + url,
      method: method,
      data: param,
      headers: {
        Authorization: LocaLtoken.load(),
      },
    });
    //处理结果
    promise
      .then((response) => {
        LocaLtoken.save(response.data);
        cb(response.data);
      })
      .catch((error) => {
        console.log(error);
        cb({
          code: 520,
          message: '请继续加油哟',
          success: false,
        });
      });
  },

  upload: (url, flie, param, cb) => {
    //文件只能FormData上传
    let formData = new FormData();
    formData.append('file', flie);
    for (let key in param) {
      formData.append(key, param[key]);
    }
    //发起请求
    let promise = axios({
      url: BASE_URL + url,
      method: 'post',
      data: formData,
      headers: {
        Authorization: LocaLtoken.load(),
        //文件上传的类型
        'Content-Type': 'multipart/form-data',
      },
    });
    promise
      .then((response) => {
        LocaLtoken.save(response.data);
        cb(response.data);
      })
      .catch((error) => {
        console.log(error);
        cb({
          code: 520,
          message: '请继续加油哟',
          success: false,
        });
      });
  },
  getUserLogo: (uid) => {
    //request_token
    return `${BASE_URL}/user/logo/${uid}?request_token=${LocaLtoken.load()}`;
  },
};

export {
  Api as default,
  Api as Api,
  LocaLtoken as LocaLtoken,
  BASE_URL as BASE_URL,
  TOKEM_KET as TOKEM_KET,
};
